//
//  AddNewModelViewController.m
//  CS Inventory Manager
//
//  Created by Billy Zoellers on 3/24/13.
//  Copyright (c) 2013 Transylvania University. All rights reserved.
//

#import "AddNewModelViewController.h"
#import "ModelSelectionNavViewController.h"
#import "ModelSelectionViewController.h"
#import "Model.h"
#import "Item.h"
#import "Type.h"

@interface AddNewModelViewController ()

@end

@implementation AddNewModelViewController

@synthesize delegate,inNewModel,inType;

-(IBAction)doneButton:(id)sender {
    
    // save to web
    // generate the URL and use %20 encoding
    NSString *ourMid = [NSString stringWithFormat:@"%d",0]; // for adding only
    NSString *ourTypeId = [NSString stringWithFormat:@"%d",inType] ;
    NSLog(@"Adding with type ID: %@",ourTypeId);
    NSString *urlStr = [NSString stringWithFormat:@"http://www.cs.transy.edu/zoellers/inventory/model.php?secret=pass&id=%@&name=%@&type=%@",ourMid,inNewModel.text,ourTypeId];
    NSString *final = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"The url is: >>>>>%@<<<<<", final);
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:final]];
    
    // make web request and catch error
    NSError * e;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&e];
    
    // log the value returned from the web server
    NSString *value = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"return from web: %@", value);
    
    // Result.
    int midFromWeb = [[[value componentsSeparatedByString:@"*"] objectAtIndex:1] integerValue];
    NSLog(@"Got back from web: %i", midFromWeb);
    
    // save locally
    Model *saveThis = [[Model alloc] init];
    [saveThis setName:inNewModel.text];
    [saveThis setModelId:midFromWeb];
    
    // update local
    [[self.delegate models] addObject:saveThis];
    [[self.delegate tableView] reloadData];
    
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"AddNewModelCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    UITextField *inputTextField = [[UITextField alloc] initWithFrame:CGRectMake(65, 10, 185, 30)];
    inputTextField.adjustsFontSizeToFitWidth = YES;
    inputTextField.textColor = [UIColor blackColor];
    inputTextField.backgroundColor = [UIColor clearColor];
    inputTextField.autocorrectionType = UITextAutocorrectionTypeNo; // no auto correction support
    inputTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; // no auto capitalization support
    inputTextField.tag = 0;
    inputTextField.clearButtonMode = UITextFieldViewModeNever; // no clear 'x' button to the right
    [inputTextField setEnabled: YES];
    [inputTextField becomeFirstResponder]; // keyboard
    
    cell.textLabel.text = @"Name";
    cell.detailTextLabel.text = @"";
    
    self.inNewModel = inputTextField;
    inputTextField.delegate = self;
    [cell.contentView addSubview:inputTextField];
    inputTextField = nil;
    
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

@end
